package com.zlm.app.emp.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zlm.common.entity.SysEmpDO;
import com.zlm.common.dto.userEmp.LoginAppParamsDto;
import com.zlm.common.dto.userEmp.SysEmpDto;
import com.zlm.app.emp.service.UserEmpService;
import com.zlm.common.util.CheckParamsUtils;
import com.zlm.common.constants.CodeConstants;
import com.zlm.common.dto.JsonResultDto;
import com.zlm.common.dto.QqResponseDto;
import com.zlm.common.dto.WechatResultDto;
import com.zlm.common.entity.UserTokenDO;
import com.zlm.common.util.QqUtils;
import com.zlm.common.util.WeChatUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * app登录Controller
 * @Author: duyufu
 * @Date: 2019/3/29 10:05
 */
@RestController
@RequestMapping(value = "/loginApp")
public class LoginController extends CheckController {

    @Autowired
    private UserEmpService userEmpService;

    /**
     * app密码登录
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/loginPwd")
    @ResponseBody
    public JsonResultDto loginPwd(LoginAppParamsDto loginAppParamsDto) {
        try {
            //校验参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkLoginPwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            JsonResultDto result = userEmpService.queryEmpByMobileAndPassword(loginAppParamsDto.getMobile(),
                    loginAppParamsDto.getPassword());
            checkJsonResultDto(result);
            JsonResultDto loginResult = userEmpService.loginEmp(loginAppParamsDto.getMobile());
            checkJsonResultDto(loginResult);
            ObjectMapper mapper = new ObjectMapper();
            SysEmpDto sysEmpDto = mapper.convertValue(loginResult.getData(), SysEmpDto.class);
            Map<String, Object> login = new HashMap<>(2);
            login.put("token",sysEmpDto.getToken());
            login.put("loginEmp",sysEmpDto);
            return success(login);
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 发送验证码
     * @param mobile
     * @return
     */
    @GetMapping("/sendVerificationCode")
    @ResponseBody
    public JsonResultDto sendVerificationCode(String mobile){
        try {
            //正则校验手机号是否格式正确
            if(!CheckParamsUtils.checkMobile(mobile)) {
                throw new RuntimeException(CodeConstants.CODE_10001);
            }
            //获取短信验证码
            JsonResultDto result = userEmpService.sendActivation(mobile);
            checkJsonResultDto(result);
            //判断用户是否已经注册
            JsonResultDto verifyResult = userEmpService.isExistMobile(mobile);
            checkJsonResultDto(verifyResult);
            Map<String,Object> phoneStatus = new HashMap<String,Object>(1);
            if ((Boolean)verifyResult.getData()){
                phoneStatus.put("phoneStatus",1);
                //用户已经注册
                return success(phoneStatus);
            }else {
                phoneStatus.put("phoneStatus",0);
                //用户未注册
                return success(phoneStatus);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 验证码注册登录
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/registerEmp")
    @ResponseBody
    public JsonResultDto registerEmp(LoginAppParamsDto loginAppParamsDto) {
        try {
            String mobile = loginAppParamsDto.getMobile();
            //校验参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkLoginAwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            JsonResultDto result = userEmpService.checkActivation(loginAppParamsDto.getActivationCode(), loginAppParamsDto.getMobile());
            checkJsonResultDto(result);
            //判断用户是否已经注册
            JsonResultDto verifyResult = userEmpService.isExistMobile(mobile);
            checkJsonResultDto(verifyResult);
            if ((Boolean)verifyResult.getData()) {
                //已注册
                throw new RuntimeException(CodeConstants.CODE_102);
            } else {
                //注册创建用户
                String password = loginAppParamsDto.getPassword();
                if (StringUtils.isBlank(password)) {
                    throw new RuntimeException(CodeConstants.CODE_10003);
                }
                JsonResultDto loginResult = userEmpService.registerEmp(mobile,password);
                checkJsonResultDto(loginResult);
                ObjectMapper mapper = new ObjectMapper();
                SysEmpDto sysEmpDto = mapper.convertValue(loginResult.getData(), SysEmpDto.class);
                Map<String, Object> login = new HashMap<>(2);
                login.put("token",sysEmpDto.getToken());
                login.put("loginEmp",sysEmpDto);
                return success(login);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 验证码注册登录
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/activationLogin")
    @ResponseBody
    public JsonResultDto activationLogin(LoginAppParamsDto loginAppParamsDto) {
        try {
            //校验参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkLoginAwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            String mobile = loginAppParamsDto.getMobile();
            JsonResultDto result = userEmpService.checkActivation(loginAppParamsDto.getActivationCode(), loginAppParamsDto.getMobile());
            checkJsonResultDto(result);
            //判断用户是否已经注册
            JsonResultDto verifyResult = userEmpService.isExistMobile(mobile);
            checkJsonResultDto(verifyResult);
            JsonResultDto loginResult;
            if ((Boolean)verifyResult.getData()) {
                //已注册
                loginResult = userEmpService.loginEmp(mobile);
                checkJsonResultDto(loginResult);
            } else {
                loginResult = userEmpService.activationLogin(mobile);
                checkJsonResultDto(loginResult);
            }
            ObjectMapper mapper = new ObjectMapper();
            SysEmpDto sysEmpDto = mapper.convertValue(loginResult.getData(), SysEmpDto.class);
            Map<String, Object> login = new HashMap<>(2);
            login.put("token",sysEmpDto.getToken());
            login.put("loginEmp",sysEmpDto);
            return success(login);
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 微信授权登录
     * @param accessToken
     * @param openid
     * @return
     */
    @GetMapping("/wechatLogin")
    @ResponseBody
    public JsonResultDto wechatLogin(String accessToken,String openid) {
        try {
            WechatResultDto userInfo = WeChatUtils.getUserInfo(accessToken, openid);
            //根据openid获取用户
            SysEmpDO emp = new SysEmpDO();
            emp.setWechatOpenid(openid);
            JsonResultDto result = userEmpService.queryEmp(emp);
            checkJsonResultDto(result);
            ObjectMapper mapper = new ObjectMapper();
            SysEmpDto sysEmp = mapper.convertValue(result.getData(), SysEmpDto.class);
            if (null == sysEmp) {
                //没有用户，创建用户
                JsonResultDto registerResult = userEmpService.wechatRegisterEmp(userInfo);
                checkJsonResultDto(registerResult);
                return success();
            }else{
                //有用户，登陆
                JsonResultDto loginResult = userEmpService.tencentLogin(emp);
                checkJsonResultDto(loginResult);
                return success(loginResult.getData());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * qq授权登录
     * @param accessToken
     * @param openid
     * @return
     */
    @GetMapping("/qqLogin")
    @ResponseBody
    public JsonResultDto qqLogin(String accessToken,String openid) {
        try {
            if (StringUtils.isBlank(accessToken)||StringUtils.isBlank(openid)) {
                throw new RuntimeException(CodeConstants.CODE_FAIL);
            }
            //根据openid获取用户
            SysEmpDO emp = new SysEmpDO();
            emp.setQqOpenid(openid);
            JsonResultDto result = userEmpService.queryEmp(emp);
            checkJsonResultDto(result);
            ObjectMapper mapper = new ObjectMapper();
            SysEmpDto sysEmp = mapper.convertValue(result.getData(), SysEmpDto.class);
            if (null == sysEmp) {
                //获取用户信息
                QqResponseDto userInfo = QqUtils.getUserInfo(accessToken,openid);
                //没有用户，创建用户
                userInfo.setOpenid(openid);
                JsonResultDto registerResult = userEmpService.qqRegisterEmp(userInfo);
                checkJsonResultDto(registerResult);
                return success();
            }else {
                JsonResultDto loginResult = userEmpService.tencentLogin(emp);
                checkJsonResultDto(loginResult);
                return success(loginResult.getData());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 绑定手机号
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/bindMobile")
    @ResponseBody
    public JsonResultDto bindMobile(LoginAppParamsDto loginAppParamsDto) {
        try {
            //校验参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkLoginAwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            JsonResultDto result = userEmpService.checkActivation(loginAppParamsDto.getActivationCode(),
                    loginAppParamsDto.getMobile());
            checkJsonResultDto(result);
            if (StringUtils.isBlank(loginAppParamsDto.getOpenid())) {
                throw new RuntimeException(CodeConstants.CODE_FAIL);
            }
            JsonResultDto bindResult = userEmpService.bindMobile(loginAppParamsDto);
            checkJsonResultDto(bindResult);
            return success(bindResult.getData());
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 根据手机号修改密码
     * @param loginAppParamsDto
     * @return
     */
    @PostMapping("/updatePassword")
    @ResponseBody
    public JsonResultDto updatePassword(LoginAppParamsDto loginAppParamsDto) {
        try {
            //检查参数
            Pair<Boolean,String> pair = CheckParamsUtils.checkUpdatePwdParams(loginAppParamsDto);
            if (!pair.getLeft()) {
                throw new RuntimeException(pair.getRight());
            }
            JsonResultDto result = userEmpService.checkActivation(loginAppParamsDto.getActivationCode(),
                    loginAppParamsDto.getMobile());
            checkJsonResultDto(result);
            JsonResultDto updateResult = userEmpService.updatePassword(loginAppParamsDto.getMobile(),
                    loginAppParamsDto.getPassword());
            checkJsonResultDto(updateResult);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

    /**
     * 根据token修改密码
     * @param token
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @GetMapping("/updatePasswordByToken")
    public JsonResultDto updatePasswordByToken(String token,String oldPassword,String newPassword) {
        try {
            //判断token失效
            UserTokenDO userToken = checkToken(token);
            JsonResultDto result = userEmpService.updatePasswordByToken(userToken.getUserId(),oldPassword,newPassword);
            checkJsonResultDto(result);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return fail(e.getMessage());
        }
    }

}
